﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WeighClient.Utils;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using WeighClient.Model;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Spire.Xls;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using DotNetSpeech;

namespace WeighClient.Windows
{
    /// <summary>
    /// WindowTest.xaml 的交互逻辑
    /// </summary>
    public partial class WindowTest : Window
    {
        SynchronizationContext _syncContext = null;
        bool tmpSteady = false;

        private String clientId = "01";
        private PortControlHelper pchSend;
        private PortControlHelper portRead = null;
        private PortControlHelper portWrite = null;
        private PortControlHelper portTest = null;
        private PortControlHelper portWeight = null;
        private IModel channel = null;
        Thread readCardThread = null;

        delegate void MyDelegate(Object value);
        SpVoice speech = null;

        public WindowTest()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;

            this.Loaded += Window_Loaded;
            
            speech = new SpVoice();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            HttpServer server = App.GetHttpServer();
            if(null != server)
            {
                HttpServer.sendMsgEvent += Server_sendMsgEvent;
            }
            
            CancellationTokenSource cts = new CancellationTokenSource();
            Task task = new Task(() => checkSteady(cts.Token), cts.Token);

            task.Start(); //任务启动

            var factory = new ConnectionFactory();
            factory.HostName = "127.0.0.1";//主机名，Rabbit会拿这个IP生成一个endpoint，这个很熟悉吧，就是socket绑定的那个终结点。
            factory.UserName = "guest";//默认用户名,用户可以在服务端自定义创建，有相关命令行
            factory.Password = "guest";//默认密码
            
            //var connection = factory.CreateConnection();
            //channel = connection.CreateModel();


            PortControlHelper readCardCom = App.GetDeviceInfo().readCardCom;
            if (null == readCardCom)
            {
                App.GetDeviceInfo().readCardCom = new PortControlHelper();
                App.GetDeviceInfo().readCardCom.OnComReceiveDataHandler += Com_DataReceived;
                readCardCom = App.GetDeviceInfo().readCardCom;
            }

            string weightCommPortName = App.GetConfig().Weight_Comm_PortName;
            if (!"".Equals(weightCommPortName))
            {
                WeightPortControlHelper weightComm = App.GetDeviceInfo().weightCom;
                if(null == weightComm)
                {
                    App.GetDeviceInfo().weightCom = new WeightPortControlHelper();
                    App.GetDeviceInfo().weightCom.OnComReceiveDataHandler += Com_Weight_DataReceived;
                    weightComm = App.GetDeviceInfo().weightCom;
                }
            }
            //if (!readCardCom.PortState)
            //{
            //    readCardCom.OpenPort("COM14", 9600, 8, 1);
            //}

            if (null == readCardThread)
            {
                readCardThread = new Thread(AutoReadCard)
                {
                    IsBackground = true
                };
                readCardThread.Start();
            }
        }
        private void ThreadGetData(CancellationToken ct)//ThreadGetData是自己的一个方法，用于每分钟读取一次数据
        {
            checkSteady(ct);
        }
        private void checkSteady(CancellationToken token)
        {
            bool isSteady = App.GetDeviceInfo().isSteady(10);
            _syncContext.Post(SetSteady, isSteady);
            Thread.Sleep(1000);
            checkSteady(token);
        }
        private void Server_sendMsgEvent(Object obj)
        {
            MyDelegate d = new MyDelegate(DealMessage);
            this.Dispatcher.Invoke(d, obj);
        }
        void DealMessage(Object obj)
        {
            JObject jsonObj = JObject.Parse(obj.ToString());
            String type = (String)jsonObj.GetValue("type");

            if ("ServerStarted".Equals(type))
            {
                _syncContext.Post(AddLogTxt, "Http Server Init.");
            }
            else if ("GetCarNo".Equals(type))
            {
                JObject detailObj = (JObject)jsonObj.GetValue("detail");
                String carNo = (String)detailObj.GetValue("carNo");
                _syncContext.Post(AddLogTxt, "识别车牌: " + carNo);
                _syncContext.Post(SetCarNo, carNo);

                //向集控端发送车号识别结果
                SendCarNoToMonitor(carNo);
                
                //向集控端发送LED显示信息
                SendVoiceTxtToMonitor(carNo + "请刷卡过磅", carNo + "请刷卡过磅");

                //开始读卡
                _syncContext.Post(AddLogTxt, "开始读卡....");
                App.GetDeviceInfo().ReadCardSuccess = false;
                App.GetDeviceInfo().DoReadCard = true;
                
                if (null == readCardThread)
                {
                    readCardThread = new Thread(AutoReadCard)
                    {
                        IsBackground = true
                    };
                    readCardThread.Start();
                }
            }
            else if ("Weight".Equals(type))
            {
                JObject detailObj = (JObject)jsonObj.GetValue("detail");
                String weight = (String)detailObj.GetValue("weight");
                _syncContext.Post(AddLogTxt, "重量: " + weight);
                _syncContext.Post(SetWeight, weight);

                //向集控端发送实时重量
                bool isSteady = App.GetDeviceInfo().isSteady(10);
                String strSteady = "不稳定";
                if (isSteady)
                {
                    strSteady = "稳定";
                }
                SendWeightToMonitor(weight, strSteady);
            }
            else if ("BillInfo".Equals(type))
            {
                JObject detailObj = (JObject)jsonObj.GetValue("detail");
                SendBillInfoToMonitor( detailObj);
            }
        }
        private void SetWeight(object text)
        {
            this.txtWeight.Text = text.ToString();
        }
        private void SetSteady(object val)
        {
            bool isSteady = (bool)val;
            if (isSteady)
            {
                txtSteady.Text = "稳定";
                txtSteady.Foreground = Brushes.Green;
            }
            else
            {
                txtSteady.Text = "不稳定";
                txtSteady.Foreground = Brushes.Red;
            }
        }

        private void Button_Click_AutoReadCard(object sender, RoutedEventArgs e)
        {
            App.GetDeviceInfo().ReadCardSuccess = false;
            readCardThread = new Thread(AutoReadCard)
            {
                IsBackground = true
            };
            readCardThread.Start();
        }
        private void AutoReadCard()
        {
            bool readCardSuccess = App.GetDeviceInfo().ReadCardSuccess;
            bool doReadCard = App.GetDeviceInfo().DoReadCard;
            if (doReadCard && !readCardSuccess)
            {
                try
                {
                    App.GetDeviceInfo().readCardCom.SendHexData("FF CC 01 58 38 31 30 36 31 38 93");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("端口COM: 打开失败!" + ex.Message);
                }
            }

            Thread.Sleep(1000);

            AutoReadCard();
        }

        private void Button_Click_ReadCard(object sender, RoutedEventArgs e)
        {
            try
            {
                portRead = new PortControlHelper();
                portRead.OnComReceiveDataHandler += Com_DataReceived;
                portRead.OpenPort("COM4", 9600, 8, 1);
                portRead.SendHexData("FF CC 01 58 38 31 30 36 31 38 93");
                Thread.Sleep(300);
                //portRead.ClosePort();

                //Thread.Sleep(200);
                //portRead.OpenPort("COM" + port, 9600, 8, 1);
                portRead.SendHexData("FF CC 01 59 38 31 30 36 31 38 92");
                Thread.Sleep(300);
                ///portRead.ClosePort();

                //Thread.Sleep(200);
                //portRead.OpenPort("COM" + port, 9600, 8, 1);
                portRead.SendHexData("FF CC 01 57 38 31 30 36 31 38 9C");
                Thread.Sleep(300);
                // portRead.ClosePort();

                //Thread.Sleep(200);
                //portRead.OpenPort("COM" + port, 9600, 8, 1);
                portRead.SendHexData("FF CC 01 52 38 31 30 36 31 38 99");
                Thread.Sleep(300);
                portRead.ClosePort();
            }
            catch (Exception ex)
            {
                MessageBox.Show("端口COM: 打开失败!" + ex.Message);
            }
            finally
            {
                if (portRead.PortState)
                {
                    portRead.ClosePort();
                }
                portRead = null;
            }
        }

        private void Com_Weight_DataReceived(String response)
        {
            _syncContext.Post(AddLogTxt, response);

            string valStr = response.Substring(10, 8);
            valStr = valStr.Substring(1, 1) + valStr.Substring(3, 1) + "." + valStr.Substring(5, 1) + valStr.Substring(7, 1);
            double dblVal = double.Parse(valStr);
            string weight = dblVal.ToString("00.00");
            App.GetDeviceInfo().Weight = dblVal;

            _syncContext.Post(AddLogTxt, dblVal.ToString("00.00"));

            _syncContext.Post(SetWeight, weight);

            //向集控端发送实时重量
            bool isSteady = App.GetDeviceInfo().isSteady(10);
            String strSteady = "不稳定";
            if (isSteady)
            {
                strSteady = "稳定";
            }
            //SendWeightToMonitor(weight, strSteady);
        }
        private void Com_DataReceived(String response)
        {
            //_syncContext.Post(addReadLog, response);
            Console.WriteLine(response);

            String[] resArray = ByteUtils.MySplit(response, 2);
            if (resArray.Length < 5) return;

            if (resArray[3] == "68")
            {
                //读GUID 32位
                if (resArray.Length < 37) return;

                String str = "";

                ASCIIEncoding ASCIITochar = new ASCIIEncoding();
                String s = "";
                for (int i = 4; i < 36; i++)
                {
                    s += resArray[i];
                }
                byte[] aa = ByteUtils.strToToHexByte(s);
                char[] ascii = ASCIITochar.GetChars(aa);

                for (int i = 0; i < ascii.Length; i++)
                {
                    str += ascii[i];
                }
                _syncContext.Post(SetGuidText, str);
                App.GetDeviceInfo().ReadCardSuccess = true;
                App.GetDeviceInfo().DoReadCard = false;
                _syncContext.Post(AddLogTxt, "读取卡GUID成功: " + str);

                App.GetDeviceInfo().CurrentGuid = str;

                
                var uploadThread = new Thread(UploadWeightInfo)
                {
                    IsBackground = true
                };
                uploadThread.Start();
            }
            else if (resArray[3] == "69")
            {
                if (resArray.Length < 21) return;

                ASCIIEncoding ASCIITochar = new ASCIIEncoding();

                //预装量
                byte[] byteNums = ByteUtils.strToToHexByte(resArray[15] + resArray[16] + resArray[17] + resArray[18] + resArray[19]);
                char[] ascii = ASCIITochar.GetChars(byteNums);
                String strNum = "";
                for (int i = 0; i < ascii.Length; i++)
                {
                    strNum += ascii[i];
                }
                _syncContext.Post(SetPlanNumText, strNum);

                //油品代码
                byte[] byteProdCode = ByteUtils.strToToHexByte(resArray[13] + resArray[14]);
                char[] prodCodeAscii = ASCIITochar.GetChars(byteProdCode);
                String strProdCode = "";
                for (int i = 0; i < prodCodeAscii.Length; i++)
                {
                    strProdCode += prodCodeAscii[i];
                }
                _syncContext.Post(SetProdCodeText, strProdCode);

                //车号
                byte[] byteCarNum = ByteUtils.strToToHexByte(resArray[7] + resArray[8] + resArray[9] + resArray[10] + resArray[11] + resArray[12]);
                char[] carNumAscii = ASCIITochar.GetChars(byteCarNum);
                String carNumCode = "";
                for (int i = 0; i < carNumAscii.Length; i++)
                {
                    carNumCode += carNumAscii[i];
                }
                _syncContext.Post(SetCarNumText, carNumCode);
            }
            else if (resArray[3] == "67")
            {
                if (resArray.Length < 13) return;

                ASCIIEncoding ASCIITochar = new ASCIIEncoding();

                //发货单号
                byte[] byteCodes = ByteUtils.strToToHexByte(resArray[4] + resArray[5] + resArray[6] + resArray[7] + resArray[8] + resArray[9] + resArray[10] + resArray[11]);
                char[] ascii = ASCIITochar.GetChars(byteCodes);
                String strNum = "";
                for (int i = 0; i < ascii.Length; i++)
                {
                    strNum += ascii[i];
                }
                _syncContext.Post(SetBillCodeText, strNum);
            }
            else if (resArray[3] == "62")
            {
                if (resArray.Length < 9) return;

                ASCIIEncoding ASCIITochar = new ASCIIEncoding();

                //IC后位
                byte[] bytes = ByteUtils.strToToHexByte(resArray[4] + resArray[5] + resArray[6] + resArray[7]);
                char[] ascii = ASCIITochar.GetChars(bytes);
                String strNum = "";
                for (int i = 0; i < ascii.Length; i++)
                {
                    strNum += ascii[i];
                }
                _syncContext.Post(SetIcCodeText, strNum);
            }
        }
        private void SetGuidText(object text)
        {
            this.txtGuid01.Text = text.ToString();
        }
        private void SetCarNo(object text)
        {
            this.txCarNo01.Text = text.ToString();
        }
        private void SetPlanNumText(object text)
        {
            this.txPlanNum01.Text = text.ToString();
        }
        private void SetProdCodeText(object text)
        {
            this.txtOilCode01.Text = text.ToString();
        }
        private void SetCarNumText(object text)
        {
            this.txCarNo01.Text = text.ToString();
        }
        private void SetBillCodeText(object text)
        {
            this.txtPass01.Text = text.ToString();
        }
        private void SetIcCodeText(object text)
        {
            this.txtIcCode01.Text = text.ToString();
        }
        
        private void AddLogTxt(object text)
        {
            this.txtLog.Text += text.ToString() + "\n";
        }

        private void UploadWeightInfo()
        {
            //根据GUID获取提单信息
            _syncContext.Post(AddLogTxt, "远程获取提单信息");
            String guid = App.GetDeviceInfo().CurrentGuid;
            Bill bill = LoadBillInfo(guid);
            bool readCardSuccess = App.GetDeviceInfo().ReadCardSuccess;
            if (!readCardSuccess) return;
            if (bill == null)
            {
                _syncContext.Post(AddLogTxt, "远程获取提单信息失败...");
                App.GetDeviceInfo().CurrentBill = null;
            }
            else
            {
                App.GetDeviceInfo().CurrentBill = bill;
                _syncContext.Post(AddLogTxt, "获取提单信息,车号: " + bill.carNo + ",提单号: " + bill.orderCode + ",ID: " + bill.id);

                //上传提单信息
                JObject detailObj = new JObject();
                detailObj.Add("billCode", bill.orderCode);

                JObject billObj = new JObject();
                billObj.Add("type", "BillInfo");
                billObj.Add("detail", detailObj);
                
                Server_sendMsgEvent(billObj);

                ReadWeight();

                UploadBillInfo(bill.id, guid, App.GetDeviceInfo().Weight.ToString());
            }
        }
        private void ReadWeight()
        {
            _syncContext.Post(AddLogTxt, "开始获取重量");
            bool interrupt = App.GetDeviceInfo().WeightInterrupt;
            bool comlete = false;
            bool readCardSuccess  = App.GetDeviceInfo().ReadCardSuccess;
            if (!readCardSuccess) return;

            while (!interrupt && !comlete && readCardSuccess)
            {
                //该线程会进行无限循环，自己不会结束
                bool isSteady = App.GetDeviceInfo().isSteady(10);
                if (isSteady)
                {
                    _syncContext.Post(AddLogTxt, "获取重量: " + App.GetDeviceInfo().Weight);
                    //App.GetDeviceInfo().CurrentBill.weight = App.GetDeviceInfo().Weight;

                    comlete = true;
                }
                else
                {
                    Thread.Sleep(1000);
                    interrupt = App.GetDeviceInfo().WeightInterrupt;
                    readCardSuccess = App.GetDeviceInfo().ReadCardSuccess;
                }
            }
        }
        private void UploadBillInfo(String id,String guid,String weight)
        {
            try
            {
                String bodyJsonStr = "{\"position\":\"" + id + "\",\"guid\":\"" + guid + "\",\"weight\":\"" + weight + "\"}";

                String result = HttpPostHelper.doHttpPost("http://192.168.1.132:8061/ytBill/tareByGuid", bodyJsonStr);
                JObject resJSON = JObject.Parse(result);
                string status = (string)resJSON.GetValue("status");

                if ("success".Equals(status))
                {
                    _syncContext.Post(AddLogTxt, "计量完成");
                }
            }
            catch (Exception ex)
            {
                _syncContext.Post(AddLogTxt, "计量失败");
            }
        }
        private void Button_Click_StartWebService(object sender, RoutedEventArgs e)
        {
            _syncContext.Post(AddLogTxt, "启动Http服务");

            HttpServer server = App.GetHttpServer();
            if (!server.IsListening())
            {
                server.Run();
                ((Button)sender).IsEnabled = false;
            }
        }

        private void Button_Click_WeightInterrupt(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            bool interrupt = App.GetDeviceInfo().WeightInterrupt;
            if (!interrupt)
            {
                App.GetDeviceInfo().WeightInterrupt = true;
                btn.Content = "恢复获取重量";
            }
            else
            {
                App.GetDeviceInfo().WeightInterrupt = false;
                btn.Content = "中断获取重量";
            }
        }

        private void Button_Click_OpenReadCardPort(object sender, RoutedEventArgs e)
        {
            
            PortControlHelper readCardCom = App.GetDeviceInfo().readCardCom;
            if(null == readCardCom)
            {
                App.GetDeviceInfo().readCardCom = new PortControlHelper();
                App.GetDeviceInfo().readCardCom.OnComReceiveDataHandler += Com_DataReceived;
                readCardCom = App.GetDeviceInfo().readCardCom;
            }
            if (!readCardCom.PortState)
            {
                readCardCom.OpenPort("COM14", 9600, 8, 1);
            }
        }

        private Bill LoadBillInfo(String guid)
        {
            Bill bill = null;

            try
            {
                String bodyJsonStr = "{\"guid\":\"" + guid + "\"}";

                String result = HttpPostHelper.doHttpPost("http://192.168.1.132:8061/ytBill/selectBillByGuid", bodyJsonStr);
                JObject resJSON = JObject.Parse(result);
                bool success = (bool)resJSON.GetValue("success");

                if (success)
                {
                    JObject detailJSON = (JObject)resJSON.GetValue("data");
                    String id = (String)detailJSON.GetValue("billNo");
                    String carNo = (String)detailJSON.GetValue("carNumber");
                    String orderCode = (String)detailJSON.GetValue("billNo");

                    bill = new Bill();

                    bill.id = id;
                    bill.orderCode = orderCode;
                    bill.carNo = carNo;
                }
            }
            catch (Exception ex) {
                bill = null;
            }

            return bill;
        }
        private void Button_Click_HttpPost(object sender, RoutedEventArgs e)
        {
            String result = HttpPostHelper.doHttpPost("http://192.168.1.132:8061/receive/tareByGuid", "{}");
            JObject resJSON = JObject.Parse(result);
            bool success = (bool)resJSON.GetValue("success");

            if (success)
            {
                JObject detailJSON = (JObject)resJSON.GetValue("detail");
                String carNo = (String)detailJSON.GetValue("carNo");
                String orderCode = (String)detailJSON.GetValue("orderCode");

                AddLogTxt("获取提单信息,车号:"+carNo+",提单号:"+orderCode);
            }
            else
            {
                AddLogTxt("http post error");
            }
            
        }

        private void Button_Click_SubscriptMQ(object sender, RoutedEventArgs e)
        {
            var consumer = new EventingBasicConsumer(channel);//消费者
            channel.BasicConsume("Queue_001_Server", true, consumer);//消费消息
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body.ToArray());

                _syncContext.Post(AddLogTxt, message);

                JObject jsonObj = JObject.Parse(message);
                string from = (string)jsonObj.GetValue("from");
                if ("monitor".Equals(from))
                {
                    string type = (string)jsonObj.GetValue("type");
                    if ("ReadCard".Equals(type))
                    {
                        App.GetDeviceInfo().ReadCardSuccess = false;
                        App.GetDeviceInfo().DoReadCard = true;
                    }
                }
            };
        }

        private void Button_Click_SendMQ(object sender, RoutedEventArgs e)
        {
            var properties = channel.CreateBasicProperties();
            properties.DeliveryMode = 1;
            
            JObject jsonObj = new JObject();
            jsonObj.Add("from", "client");
            jsonObj.Add("clientId", "01");
            jsonObj.Add("type", "GetCarNo");
            jsonObj.Add("carNo", "鲁E05A26");

            string message = jsonObj.ToString();

            channel.BasicPublish("", "Queue_001", properties, Encoding.UTF8.GetBytes(message)); //生产消息

        }

        private void Button_Click_LinkMQ(object sender, RoutedEventArgs e)
        {
            /*
            var factory = new ConnectionFactory();
            factory.HostName = "192.168.1.127";//主机名，Rabbit会拿这个IP生成一个endpoint，这个很熟悉吧，就是socket绑定的那个终结点。
            factory.UserName = "admin";//默认用户名,用户可以在服务端自定义创建，有相关命令行
            factory.Password = "admin";//默认密码

            using (var connection = factory.CreateConnection())//连接服务器，即正在创建终结点。
            {
                //创建一个通道，这个就是Rabbit自己定义的规则了，如果自己写消息队列，这个就可以开脑洞设计了
                //这里Rabbit的玩法就是一个通道channel下包含多个队列Queue
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("Queue_001", false, false, false, null);//创建一个名称为kibaqueue的消息队列

                    var consumer = new EventingBasicConsumer(channel);//消费者
                    channel.BasicConsume("kibaQueue", true, consumer);//消费消息
                    consumer.Received += (model, ea) =>
                    {
                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body.ToArray());

                        _syncContext.Post(AddLogTxt, message);
                    };

                    var properties = channel.CreateBasicProperties();
                    properties.DeliveryMode = 1;
                    string message = "I am Kiba518"; //传递的消息内容
                    channel.BasicPublish("", "kibaQueue", properties, Encoding.UTF8.GetBytes(message)); //生产消息
                    Console.WriteLine($"Send:{message}");
                }
            }
            */
        }

        private void Button_Click_WriteCard(object sender, RoutedEventArgs e)
        {
            txtGuid02.Text = CardUtil.getCardGUID();
            
            String code = CardUtil.getCardGUIDCode(txtGuid02.Text);
            AddLogTxt(code);

            String carNumCode = CardUtil.getCarNumCode(txCarNo02.Text, txtOilCode02.Text, txPlanNum02.Text);
            AddLogTxt(carNumCode);

            String icCode = CardUtil.getIcCode(txtIcCode02.Text);
            AddLogTxt(icCode);

            String billCode = CardUtil.getBillCode(txtPass02.Text);
            AddLogTxt(billCode);
            PortControlHelper writeCardCom = App.GetDeviceInfo().readCardCom;
            try
            {
                //portWrite = new PortControlHelper();
                //portWrite.OnComReceiveDataHandler += Com_DataReceived;
                //portWrite.OpenPort("COM14", 9600, 8, 1);
                writeCardCom.SendHexData(code);
                Thread.Sleep(300);

                writeCardCom.SendHexData(carNumCode);
                Thread.Sleep(300);

                writeCardCom.SendHexData(icCode);
                Thread.Sleep(300);

                writeCardCom.SendHexData(billCode);
                Thread.Sleep(300);
                
                //portWrite.ClosePort();
            }
            catch (Exception ex)
            {
                MessageBox.Show("端口COM: 打开失败!" + ex.Message);
            }
            finally
            {
                //if (portWrite.PortState)
                //{
                //    portWrite.ClosePort();
                //}
                //portWrite = null;
            }
        }

        private void SendCarNoToMonitor(String carNo)
        {
            var properties = channel.CreateBasicProperties();
            properties.DeliveryMode = 1;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "client");
            jsonObj.Add("clientId", clientId);
            jsonObj.Add("type", "GetCarNo");
            jsonObj.Add("carNo", carNo);

            string message = jsonObj.ToString();

            channel.BasicPublish("", "Queue_001_Client", properties, Encoding.UTF8.GetBytes(message)); //生产消息
        }

        private void SendWeightToMonitor(String weight, String steady)
        {
            var properties = channel.CreateBasicProperties();
            properties.DeliveryMode = 1;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "client");
            jsonObj.Add("clientId", clientId);
            jsonObj.Add("type", "Weight");
            jsonObj.Add("weight", weight);
            jsonObj.Add("steady", steady);

            string message = jsonObj.ToString();

            channel.BasicPublish("", "Queue_001_Client", properties, Encoding.UTF8.GetBytes(message)); //生产消息
        }

        private void SendVoiceTxtToMonitor(String voiceMsg,String ledMsg)
        {
            var properties = channel.CreateBasicProperties();
            properties.DeliveryMode = 1;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "client");
            jsonObj.Add("clientId", clientId);
            jsonObj.Add("type", "VoiceAndLed");
            jsonObj.Add("voiceMsg", voiceMsg);
            jsonObj.Add("ledMsg", ledMsg);

            string message = jsonObj.ToString();

            channel.BasicPublish("", "Queue_001_Client", properties, Encoding.UTF8.GetBytes(message)); //生产消息
        }

        private void SendBillInfoToMonitor(JObject billObj)
        {
            var properties = channel.CreateBasicProperties();
            properties.DeliveryMode = 1;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "client");
            jsonObj.Add("clientId", clientId);
            jsonObj.Add("type", "BillInfo");
            jsonObj.Add("billObj", billObj);

            string message = jsonObj.ToString();

            channel.BasicPublish("", "Queue_001_Client", properties, Encoding.UTF8.GetBytes(message)); //生产消息
        }
        private void Button_Click_OpenDoor(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_OpenWeightPort(object sender, RoutedEventArgs e)
        {
            if (App.GetDeviceInfo().weightCom.IsOpen()) return;
            App.GetDeviceInfo().weightCom.OpenPort(
                App.GetConfig().Weight_Comm_PortName,9600,8,1
                );
        }

        private void Button_Click_XiaoPiao(object sender, RoutedEventArgs e)
        {
            double d1 = double.Parse("0.02");
            if (d1 >= 0.05)
            {
                MessageBox.Show("大于等于");
            }
            else
            {
                MessageBox.Show("小于");
            }
            return;
            Excel.Application ExcelApp = new Excel.Application();
            ExcelApp.Visible = false;//是打开可见

            Excel.Workbooks wbks = ExcelApp.Workbooks;

            Excel._Workbook wbk = wbks.Add("d:\\test01.xlsx");
            wbk.PrintOutEx();

            wbk.Close();//关闭文档

            wbks.Close();//关闭工作簿

            ExcelApp.Quit();//关闭excel应用程序

            System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);//释放excel进程

            ExcelApp = null;
        }

        private void Button_Click_VoiceTest(object sender, RoutedEventArgs e)
        {
            speak(AddBlank(txCarNo01.Text));
        }

        private string AddBlank(String data)
        {
            char[] charArr = data.ToCharArray();
            StringBuilder sb = new StringBuilder();
            foreach (char c in charArr)
            {
                if (c != ' ')
                {
                    sb.Append(c);
                    sb.Append(" ");
                }
                else
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }
        private void speak(String message)
        {
            try
            {
                speech.Speak(string.Empty, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
                if (null != message)
                {
                    speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);
                }
            }
            catch (Exception ex) { }
        }
    }
}
